#!/usr/bin/python3
# -*- coding:utf-8 -*-
# Create your views here.

from shutil import copyfile

import jsonpath

from django.conf import settings
from django.http import JsonResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect

from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET, require_POST
from django.views.decorators.clickjacking import xframe_options_sameorigin
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from werkzeug.utils import secure_filename
from djangoProject.settings import BASE_DIR

from job.src.function.basic_opration import *
from job.src.function.record_log import mylog
from markdown.models import MdFiles, MdSpace
from job.views import webPage
from markdown.src import __initData__
from markdown.src.tools import db

redis_obj = db.RedisDB(settings)

# --------------------------------markdown.html-----------------------------------------

md_cur_dict = {'fileExt': None, 'cur_filename': ''}
class Editor(View):
    os.chdir(BASE_DIR)
    context = {}
    context.update(webPage)
    context['has_permission'] = True
    md_list = list(MdSpace.objects.filter(type='space').values())
    upload_option = jsonpath.jsonpath(md_list, '$..space')
    upload_path = jsonpath.jsonpath(md_list, '$..upload_dir')
    space_dic = dict(zip(upload_option, upload_path))
    def post(self, request):
        filepath = request.POST.get('filepath')
        space = request.POST.get('option')
        self.upload_option.remove(space)
        self.upload_option.insert(0, space)
        self.context['upload_option'] = self.upload_option
        md_path = self.space_dic.get(space, self.upload_path[0])
        mylog.info(f'filepath: {filepath}')
        files = MdFiles.objects.filter(upload_dir=md_path).values('upload_dir', 'upload_name')
        filenames = [unit['upload_dir'] + unit['upload_name'] for unit in list(files)]
        filenames.insert(0, filepath)  # 将其插入第1个
        md_cur_dict['cur_filename'] = filepath
        self.context['filepath'] = filepath
        self.context['fileList'] = filenames
        cur_editors = get_editor(request, filepath)
        self.context['cur_editor'] = cur_editors
        self.context['content'] = read_file(filepath)
        return render(request, 'markdown.html', self.context)

    @method_decorator(login_required)
    def get(self, request):
        create_dir(self.upload_path)
        filepath = request.GET.get('filename', None)
        space = request.GET.get('space', self.upload_option[0])
        self.upload_option.remove(space)
        self.upload_option.insert(0, space)
        if filepath:
            cur_name = get_editor(request, filepath)
            md_content = read_file(filepath)
            http = webPage.get("static_url", "http://127.0.0.1:8002/static")
            md_content = re.sub(r'http://(\d.*)/static', http, md_content)
            # content_md = re.sub(r'\(\./static', f"({http}", md_content)
            filenames = [filepath]
            md_cur_dict['cur_filename'] = filepath
            c_md = {"content": md_content, "fileList": filenames, "filepath": filepath,
                    "upload_option": self.upload_option, "cur_editor": cur_name}
        else:
            md_path = self.space_dic.get(space, self.upload_path[0])
            files = MdFiles.objects.filter(upload_dir=md_path).values('upload_dir', 'upload_name')
            filenames = [unit['upload_dir'] + unit['upload_name'] for unit in list(files)]
            c_md = {"content": "", "fileList": filenames, "upload_option": self.upload_option, "cur_editor": ""}
        self.context.update(c_md)
        return render(request, 'markdown.html', self.context)

def get_editor(request, filepath):
    path, name = os.path.split(filepath)
    cur_name = request.COOKIES.get('name', '')
    cur_editor = MdFiles.objects.filter(upload_name=name).values('cur_editor')
    cur_editor = cur_editor[0]['cur_editor'].split(',') if cur_editor else []
    cur_editor.insert(0, cur_name)
    cur_name = ','.join(list(set(cur_editor)))
    cur_editor = cur_name.lstrip(',')
    MdFiles.objects.filter(upload_name=name).update(cur_editor=cur_editor)
    return cur_editor

def exitEditor(request):
    type = request.GET.get('type')
    filepath = request.GET.get("filename", None)
    cur_name = request.COOKIES.get("name", None)
    if filepath and cur_name:
        path, name = os.path.split(filepath)
        cur_editor = MdFiles.objects.filter(upload_name=name).values('cur_editor')
        cur_editor = cur_editor[0]['cur_editor'].split(',') if cur_editor else []
        cur_editor = list(set(cur_editor))
        if cur_name in cur_editor:
            cur_editor.remove(cur_name)
            new_editor = ','.join(cur_editor)
            MdFiles.objects.filter(upload_name=name).update(cur_editor=new_editor.lstrip(','))
    if type:
        return JsonResponse({'tip': '退出编辑ok，若继续编辑保存，有被他人直接覆盖造成新增内容丢失的可能性！'})
    else:
        return redirect("/markdown/fileList/")

@require_POST
@csrf_exempt
@xframe_options_sameorigin
def uploadImage(request):
    '''
    上传图片
    :return: {
        success : 0 | 1, //0表示上传失败;1表示上传成功
        message : "提示的信息",
        url     : "图片地址" //上传成功时才返回
    }
    '''
    res = {'success': 0, 'message': ''}
    cur_file = md_cur_dict['cur_filename']
    if cur_file:
        space = cur_file.split('/')[3]
        cur_path = split_path(cur_file)
        mylog.info(cur_path)
        img_dir = cur_path[2].split('_')[0]   # 分割文件名，只取 _ 前半部分，放弃之后的日期 20211116
        save_path = 'static/uploadImage/' + space + '/' + img_dir
    else:
        save_path = 'static/uploadImage/images'
        space = "image"
    is_dir_exist(save_path)
    f = None
    f1 = request.FILES.get('editormd-image-file', None)
    f2 = request.FILES.get('file', None)
    if f1:
        f = f1
    if f2:
        f = f2
    if f:
        fname = f.name
        name, ext = os.path.splitext(fname)
        filename = secure_filename(fname)
        if filename:
            cur_date = get_curtime('%Y%m%d%H%M%S')
            newName = cur_date + ext
            # 存储到数据库
            upload_dir = './' + save_path + '/'
            data = {"doc_type": ext, "space": space, "upload_dir": upload_dir, "upload_name": newName, "cn_name": fname}
            MdFiles(**data).save()
            save_path = upload_dir + newName
            # save_name = path + '/' + f.name
            destination = open(save_path, 'wb+')
            for chunk in f.chunks():
                destination.write(chunk)
            destination.close()
            mylog.info(f"url: {save_path}")
            http = webPage.get("static_url", "http://127.0.0.1:8002/static")
            http_rpl = http.rstrip("static")
            res_url = http_rpl + save_path
            res.update({'success': 1, 'message': 'Upload successfully!', 'url': res_url, 'type': ext, 'filename': newName})
        else:
            res.update({'success': 0, 'message': 'Upload fail!', 'url': save_path})
    else:
        res.update({'success': 0, 'message': 'No image!'})
    return JsonResponse(res)

@require_POST
@csrf_exempt
def modify_markdown(request):
    space = request.POST.get('option')
    filepath = request.POST.get('filepath')
    cur_editors = request.POST.get('cur_editors')
    # cur_editors = cur_editors.split(':')[1] if cur_editors else ''
    mylog.info(f'cur_editors: {cur_editors}')
    content_md = request.POST.get('content_md')
    mylog.info(f'filepath: {filepath}')
    fp, fn = os.path.split(filepath)
    name, ext = os.path.splitext(fn)
    cur_name = request.COOKIES.get('name', None)
    # cur_editor = MdFiles.objects.filter(upload_name=fn).values('cur_editor')
    cur_editors = cur_editors.split(',') if cur_editors else []
    cur_editor = list(set(cur_editors))
    if len(cur_editor) <= 1:   # 如果查看的是历史保存的，则不再重复进行保存
        delete_file(filepath)
        write_file(filepath, content_md)
        # MdFiles.objects.filter(upload_name=fn).update(text_content=content_md)
        response_info = f'{fn} 文件保存成功！'
    else:
        new_name = name + '_' + get_curtime('%Y%m%d%H%M%S') + ext
        new_dir = fp + '/' + 'temp/'
        new_fn = new_dir + new_name
        is_dir_exist(new_dir)
        # copyfile(filepath, new_fn)
        write_file(new_fn, content_md)
        data = {"doc_type": ext, "space": space, "upload_dir": new_dir, "upload_name": new_name,
                "cn_name": f'{cur_name}暂存文件'}    # "text_content": content_md // 文本保存到数据库取消
        MdFiles(**data).save()
        response_info = f'因文件正在被多人编辑，为确保不被覆盖，文件暂存{new_fn}；\n通知他人退出编辑后再合入保存！'
        mylog.info(response_info)
    return JsonResponse({'res': response_info})

# --------------------------------filelist.html-----------------------------------------

class FileList(View):
    context = {}
    context.update(webPage)
    context['has_permission'] = True
    os.chdir(BASE_DIR)
    md_list = list(MdSpace.objects.filter(type='space').values())
    upload_option = jsonpath.jsonpath(md_list, '$..space')
    upload_path = jsonpath.jsonpath(md_list, '$..upload_dir')
    space_dic = dict(zip(upload_option, upload_path))

    @method_decorator(login_required)
    def get(self, request):
        space = request.GET.get('space', self.upload_option[0])
        filepath = request.GET.get('path', self.space_dic[space])
        mylog.info("space:" + space)
        mylog.info("filepath:" + filepath)
        self.get_data(space, filepath)
        return render(request, 'filelist.html', self.context)

    def post(self, request):
        space_key = request.POST.get('space')
        space_path = self.space_dic[space_key]
        res = MdFiles.objects.filter(doc_type='dir', space=space_key, upload_dir=space_path).exists()
        if not res:
            data = {'doc_type': 'dir', 'space': space_key, 'upload_dir': space_path, 'upload_name': space_key,
                    'cn_name': f'{space_key}的子目录'}
            MdFiles(**data).save()
            is_dir_exist(space_path)
        self.get_data(space_key, space_path)
        return render(request, 'filelist.html', self.context)

    def get_data(self, space, path):
        # 返回左侧的返回目录列表数据
        if space == "All":
            data_files = MdFiles.objects.values('space', 'upload_dir').distinct().order_by('upload_dir')
        else:
            data_files = MdFiles.objects.filter(space__startswith=space).values('space', 'upload_dir').distinct().order_by('upload_dir')
        data_files = list(data_files)
        mylog.info(data_files)
        self.context['dirList'] = self.subName(data_files)
        # 返回右侧的文件列表数据
        files = MdFiles.objects.filter(upload_dir=path).exclude(doc_type='dir').values('doc_type', 'upload_dir', 'upload_name', 'cn_name')
        # 增加如果是 .xlsx 类型用 edit_excel 编辑，否则用 edit_markdown 编辑器  2021-12-1
        self.context['filenames'] = [{'filepath': unit['upload_dir'] + unit['upload_name'], 'space': space, 'doc_type': unit['doc_type'],
            'filename': unit['upload_name'], 'description': unit['cn_name']} for unit in files]
        # 子目录重新排序
        self.upload_option.remove(space)
        self.upload_option.insert(0, space)
        self.context['upload_option'] = self.upload_option
        return self.context

    def subName(self, files: list) -> list:
        res_list = []
        for unit in files:
            dirname = unit['upload_dir'].split('static/')[1].replace('/', '.').rstrip('.')
            dirname = dirname.replace('markdown', '文档') if re.match(r'markdown', dirname) else dirname
            dirname = dirname.replace('uploadImage', '附件') if re.match(r'uploadImage', dirname) else dirname
            cur_dic = {'path': unit['upload_dir'], 'space': unit['space'], 'name': dirname}
            res_list.append(cur_dic)
        return res_list


@require_GET
def deleteFile(request):
    filepath = request.GET.get('filename')
    space = request.GET.get('space')
    fpath, fname = os.path.split(filepath)
    # 删除本地文件和数据库的文件路径存储信息
    delete_file(filepath)
    MdFiles.objects.filter(upload_name=fname).delete()
    return HttpResponseRedirect(f'/markdown/fileList/?path={fpath}/&space={space}')

@require_POST
@csrf_exempt
def deleteDir(request):
    context = {}
    link = request.POST.get('link')
    res = re.search(r'path=(.*).space=(.*)', link)
    if res:
        path, space = res[1], res[2]
        mylog.info(f'path: {path}')
    else:
        context['res'] = 'error! No path or space!'
        return JsonResponse(context)
    # 删除本地文件和数据库的文件路径存储信息
    files = os.listdir(path)
    if files:
        context['res'] = f'{path} 目录不为空，不能删除！'
        return JsonResponse(context)
    del_path = path.rstrip('/')
    delete_dir(del_path)
    fname = del_path.split('/')[-1]
    MdFiles.objects.filter(upload_name=fname).delete()
    context['res'] = f'{fname}目录已经删除！'
    return JsonResponse(context)

def getDirList(request):
    space = request.GET.get('space', 'common')
    mylog.info(f'space_key:{space}')
    # 返回左侧的返回目录列表数据
    if space == "All":
        data_files = MdFiles.objects.values('upload_dir').distinct()
    else:
        data_files = MdFiles.objects.filter(space__startswith=space).values('upload_dir').distinct()
    data_files = list(data_files)
    dirs_dict = [{'path': unit['upload_dir'], 'space': space,
                'name': unit['upload_dir'].split('static/')[1].replace('/', '.').rstrip('.')}
               for unit in data_files]
    return render(request, 'filelist_tableL.html', {"dirList": dirs_dict})

@require_POST
@csrf_exempt
def get_filelist(request):
    md_list = list(MdSpace.objects.filter(type='space').values())
    upload_option = jsonpath.jsonpath(md_list, '$..space')
    upload_path = jsonpath.jsonpath(md_list, '$..upload_dir')
    space_dic = dict(zip(upload_option, upload_path))
    req = request.POST
    opt_value = req.get('option_type')
    isHistory = req.get('flag')
    md_path = space_dic.get(opt_value, upload_option[0])
    if isHistory == 'true':
        md_path = md_path + 'history/'
    filelist = MdFiles.objects.filter(upload_dir=md_path).values('upload_dir', 'upload_name')
    filelist = [unit['upload_dir'] + unit['upload_name'] for unit in list(filelist)]
    return JsonResponse({"filelist": filelist})

def getSpaceList(request):
    spaceLst = MdSpace.objects.exclude(space='All').values("space")
    mylog.info(spaceLst)
    return JsonResponse({"spaceList": list(spaceLst)})

def getSpaceDirsList(request):
    space = request.GET.get('space')
    dirLst = MdFiles.objects.filter(space=space, upload_dir__contains='/markdown/').values("upload_dir").distinct()
    newlist = list()
    for unit in list(dirLst):
        unit['upload_dir'] = unit['upload_dir'].rstrip('/')
        mylog.info(f"unit: {unit}")
        newlist.append(unit)
    mylog.info(newlist)
    return JsonResponse({"spaceDirsList": newlist})

def moveFile(request):
    raw_file = request.POST.get('title')
    space = request.POST.get('space')
    upload_dir = request.POST.get('target_path')
    res = re.search(r'filename=(.*);space=(.*)', raw_file)
    if res:
        filename, raw_space = res[1], res[2]
        file = split_path(filename)
        new_file = upload_dir + '/' + file[1]
        copyfile(filename, new_file)
        MdFiles.objects.filter(upload_name=file[1]).update(upload_dir=upload_dir + '/', space=space)
        delete_file(filename)
    else:
        new_file = "源文件不存在，无法移动！"
    mylog.info(f"new_file: {new_file}")
    return JsonResponse({"res": new_file})

# --------------------------------upload.html-----------------------------------------
def handle_uploaded_file(f, save_name):
    with open(save_name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

class UploadFile(View):
    context = {}
    md_list = list(MdSpace.objects.filter(type='space').values())
    upload_option = jsonpath.jsonpath(md_list, '$..space')
    upload_path = jsonpath.jsonpath(md_list, '$..upload_dir')
    context['upload_option'] = upload_option
    space_dic = dict(zip(upload_option, upload_path))
    create_dir(upload_path)
    def post(self, request):
        path_key = request.POST.get('op_type')
        upload_dir = request.POST.get('link')     # 上传时直接传递目录 20211126
        # upload_dir = self.space_dic[path_key]
        description = request.POST.get('description', None)
        f = request.FILES.get('file', None)
        if f:
            filename = f.name
            fn, ext = os.path.splitext(filename)
            save_name = upload_dir + filename
            # 上传文件保存到数据库
            data = {"doc_type": ext, "space": path_key, "upload_dir": upload_dir,
                    "upload_name": filename, "cn_name": description}
            exit_res = MdFiles.objects.filter(upload_name=filename).values().exists()
            if not exit_res:
                is_dir_exist(upload_dir)
                destination = open(save_name, 'wb+')
                for chunk in f.chunks():
                    destination.write(chunk)
                destination.close()
                MdFiles(**data).save()
                self.context['upload_path'] = save_name
            else:
                self.context['upload_path'] = f'{filename} 文件已存在，不允许文件名重复！'
            return render(request, 'upload.html', self.context)
        else:
            return render(request, 'upload.html', self.context)

    def get(self, request):
        param = request.GET.get('link', '')
        space = request.GET.get('space', '')
        res = re.search(r'path=(.*)', param)
        if res:
            self.context['link'] = res[1]
            self.context['upload_option'] = [space]
        mylog.info(self.context)
        return render(request, 'upload.html', self.context)

@require_POST
@csrf_exempt
def uploadFileDiv(request):
    context = {}
    link = request.POST.get('link')
    fileType = request.POST.get('fileType', 'false')
    description = request.POST.get('description', '')
    mylog.info(f'link: {link}, description: {description}, fileType: {fileType}')
    f = request.FILES.get('file', None)
    mylog.info(f'files: {f}')
    res = re.search(r'path=(.*).space=(.*)', link)
    if res:
        upload_dir, space = res[1], res[2]
    else:
        context['upload_path'] = 'error! No path or space!'
        return JsonResponse(context)
    is_dir_exist(upload_dir)

    if f:
        filename = f.name
        fn, ext = os.path.splitext(filename)
        save_name = upload_dir + filename
        if fileType == 'true':
            ext = '.xlsx'
            secname = fn + ext
            description += f' 上传的Excel类型文件 {secname}'
        # 上传文件保存到数据库
        data = {"doc_type": ext, "space": space, "upload_dir": upload_dir,
                "upload_name": filename, "cn_name": description}
        exit_res = MdFiles.objects.filter(upload_name=filename).values().exists()
        if not exit_res:
            is_dir_exist(upload_dir)
            destination = open(save_name, 'wb+')
            for chunk in f.chunks():
                destination.write(chunk)
            destination.close()
            MdFiles(**data).save()
            context['upload_path'] = save_name
        else:
            context['upload_path'] = f'{filename} 文件已存在，不允许文件名重复！'
        return JsonResponse(context)
    else:
        context['upload_path'] = 'No file found!'
        return JsonResponse(context)

@require_POST
@csrf_exempt
def createFile(request):
    context = {}
    link = request.POST.get('link', '')
    name = request.POST.get('fileName')
    ext = request.POST.get('filetype')
    res = re.search(r'path=(.*).space=(.*)', link)
    if res:
        path, space = res[1], res[2]
    else:
        context['res'] = 'error! No path or space!'
        return JsonResponse(context)
    # 判断如果是文件，
    if ext == 'dir':
        filename = name
        upload_dir = path + name + '/'
        mylog.info(f'新增文件夹：{upload_dir}')
        is_dir_exist(upload_dir)
        desc = '这是一个目录'
    else:
        upload_dir = path
        fn = name.split('.')
        fname = fn[0] if len(fn) > 1 else name
        fn_ext = fn[1] if len(fn) > 1 else ext  # 给了后缀用真名
        if fn_ext == '.xlsx':
            if check_contain_chinese(fname.encode('utf-8')):
                jname = "excel_" + get_curtime("%Y%m%d%H%M%S")
            else:
                jname = fname
            filename = jname + '.json'
            desc_name = fname + fn_ext
            desc = f'新建Excel类型文件 {desc_name}'
        elif fn_ext == '.md':
            filename = fname + fn_ext
            desc = f'新建Markdown类型文件 {filename}'
        else:
            filename = fname + fn_ext
            desc_name = name
            desc = f'新建文件 {desc_name}'
    # 数据库更新参数
    data = {"doc_type": ext, "space": space, "upload_dir": upload_dir,
            "upload_name": filename, "cn_name": desc}
    exit_res = MdFiles.objects.filter(upload_name=filename).values().exists()
    if not exit_res:
        filepath = path + filename
        if not os.path.exists(filepath) and ext != 'dir':
            if data['doc_type'] == '.xlsx':
                content = __initData__.sheetInitData
                sheet_json = {"data": content}
                # data.update({"text_content": json.dumps(sheet_json)})   // 文本保存到数据库取消
                write_json(filepath, sheet_json)
            else:
                with open(filepath, 'w', encoding='utf-8') as f:
                    f.write('')
                # data.update({"text_content": ""})
        MdFiles(**data).save()
        context['res'] = f"{filename}文件已新增成功"
    else:
        context['res'] = f"{filename}文件已存在"
    return JsonResponse(context)


# --------------------------------view_md.html-----------------------------------------
@require_GET
def view_markdown(request):
    context = {}
    context.update(webPage)
    filename = request.GET.get('filename')
    content = read_file(filename)
    http = webPage.get("static_url", "http://127.0.0.1:8001/static")
    content = re.sub(r'http://(\d.*)/static', http, content)
    res_data = {'content': content, 'filename': filename}
    context['content'] = res_data
    return render(request, 'view_md.html', context)


@require_GET
def query_config(request):
    res1 = MdFiles.objects.all()
    res2 = MdFiles.objects.values()
    # print(f"res1: {res1}")
    # print(f"res2: {res2}")
    return JsonResponse({"status": "successful"})


# ------------------- edit excel table --------------

class EditExcel(View):
    context = {}
    context.update(webPage)
    context['has_permission'] = True

    @method_decorator(login_required)
    def get(self, request):
        # name = request.COOKIES.get('name', '')
        # filename = './static/markdown/ljk/test.json'
        space = request.GET.get('space', 'common')
        filename = request.GET.get('filename')
        if not filename:
            filename = './static/markdown/common/excel/LuckysheetDemo.json'
            self.context['next_url'] = "/markdown/fileList/"
            self.context['load_local'] = False
            self.context['sheet_title'] = 'LuckysheetDemo'
        else:
            self.context['load_local'] = True
            content = read_json(filename)
            self.context['option_data'] = json.dumps(content)
            mylog.info(content)
            file = split_path(filename)
            next_path = file[0] + '/'
            self.context['next_url'] = "/markdown/fileList/?path=" + next_path + "&space=" + space
            self.context['sheet_title'] = file[1]
        get_editor(request, filename)   # 更新当前编辑者到数据库
        self.context['space'] = space
        self.context['filename'] = filename
        return render(request, 'tableEdit.html', self.context)

    @csrf_exempt
    def post(self, request):
        mylog.info("post request")
        gridkey = request.POST.get("gridKey", None)
        mylog.info("gridkey: %s" % gridkey)
        init_json = __initData__.sheetInitData
        # 该判断是为了在用户刚开始上传excel的时候，点击保存数据库之后，从redis再加载一边数据，作为协同使用
        if gridkey:

            fileinfo = MdFiles.objects.filter(upload_name=gridkey).first()
            if fileinfo:
                filepath = fileinfo.upload_dir + fileinfo.upload_name
                mylog.info(f"filepath: {filepath}")
                init_json = json.dumps(read_json(filepath))
            else:
                init_json = json.dumps(init_json)
        else:
            init_json = json.dumps(init_json)
        return HttpResponse('%s' % init_json)

@require_POST
@csrf_exempt
def saveSheet(request):
    context = {}
    celldata = request.POST.get('content')
    filepath = request.POST.get('filename')
    space = request.POST.get('space', 'common')
    mylog.info(f"celldata: {celldata}")
    file = split_path(filepath)
    is_dir_exist(file[0])
    filename = file[1]

    # 数据库更新参数
    data = {"doc_type": '.xlsx', "space": space, "upload_dir": file[0] + '/',
            "upload_name": filename, "cn_name": '保存Excel：' + file[2] + '.xlsx'}
    exit_res = MdFiles.objects.filter(upload_name=filename).values().exists()
    if not exit_res:
        MdFiles(**data).save()
    wr = write_json(filepath, json.loads(celldata))
    context['res'] = f"保存结果：{wr}"
    return JsonResponse(context)

@require_POST
@csrf_exempt
def queryEditor(request):
    context = {}
    name = request.COOKIES.get('name', '')
    filepath = request.POST.get('filename')
    # space = request.POST.get('space', 'common')
    file = split_path(filepath)
    mylog.info(file)
    res = MdFiles.objects.filter(upload_name=file[1]).first()
    if res:
        editors = res.cur_editor
        mylog.info(f'editors: {editors}')
        editorlst = editors.split(',')
        # editorlst = editorlst.remove(name) if name in editorlst else editorlst
        if len(editorlst) <= 1:
            context['flag'] = True
            context['tip'] = '当前无其他人共同编辑，可直接保存！'
            context['filename'] = filepath
        else:
            context['flag'] = False
            newfilename = file[0] + '/temp/' + file[2] + '_' + name + file[3]
            cur_editors = ','.join(editorlst)
            cur_editors = cur_editors.lstrip(',')
            context['tip'] = f'当前存在其他人共同编辑，不可直接保存！\r\n将暂存到：{newfilename}\r\n' \
                             f'当前编辑者：{cur_editors}，待他人退出编辑后再合入！'
            context['filename'] = newfilename
    else:
        context['flag'] = True
        context['tip'] = '当前无人编辑，可直接保存！'
        context['filename'] = filepath
    return JsonResponse(context)

def viewDemo(request):
    return render(request, 'LuckysheetDemo.html')


# ---------------------------sheet + redis------------------------------------------------------------

from django.shortcuts import HttpResponse
# 页面数据初始化加载
class LuckySheetLoadUrl(View):
    context = {}
    context.update(webPage)
    context['has_permission'] = True

    @method_decorator(login_required)
    def get(self, request):
        space = request.GET.get('space', 'common')
        filename = request.GET.get('filename')
        if not filename:
            filename = './static/markdown/common/excel/'
            self.context['next_url'] = f"/markdown/fileList/?path={filename}&space=common"
            self.context['sheet_title'] = '示例文件 LuckysheetDemo.xlsx'
            self.context['sheet_filename'] = 'LuckysheetDemo.json'
        else:
            file = split_path(filename)
            next_path = file[0] + '/'
            fileCN = MdFiles.objects.filter(upload_name=file[1]).first()
            self.context['next_url'] = "/markdown/fileList/?path=" + next_path + "&space=" + space
            self.context['sheet_title'] = fileCN.cn_name
            self.context['sheet_filename'] = file[1]
        self.context['filename'] = filename
        return render(request, 'sheetEdit.html', self.context)

    def post(self, request):
        mylog.info("post request")
        gridkey = request.POST.get("gridKey", 'LuckysheetDemo.json')
        mylog.info("gridkey: %s" % gridkey)
        init_json = __initData__.sheetInitData
        # 该判断是为了在用户刚开始上传excel的时候，点击保存数据库之后，从redis再加载一边数据，作为协同使用
        if gridkey:
            redis_json = redis_obj.get_string("sheet:" + gridkey)
            if redis_json != -1:
                redi_json = json.loads(redis_json)
                init_json = json.dumps(redi_json.get("data"))
            else:
                fileExit = MdFiles.objects.filter(upload_name=gridkey).exists()
                if fileExit:
                    fileinfo = MdFiles.objects.filter(upload_name=gridkey).first()
                    filepath = fileinfo.upload_dir + fileinfo.upload_name
                    mylog.info(f"filepath: {filepath}")
                    sheet_json = read_json(filepath)
                    redis_json = json.dumps(sheet_json)
                else:
                    data = {"doc_type": '.xlsx', "space": 'common', "upload_dir": './static/markdown/common/excel/',
            "upload_name": gridkey, "cn_name": '新增的LuckysheetDemo.xlsx'}
                    MdFiles(**data).save()
                    sheet_json = {"data": init_json}
                    demo_path = data['upload_dir'] + data['upload_name']
                    write_json(demo_path, sheet_json)
                    redis_json = json.dumps(sheet_json)
                res = redis_obj.insert_string("sheet:" + gridkey, redis_json)
                redis_obj.set_expireat(gridkey, save_time=3*24*60*60)
                mylog.info(f"inset into redis:{res}")
                init_json = json.dumps(sheet_json.get("data"))
        else:
            gridkey = 'LuckysheetDemo.json'
            res = redis_obj.insert_string("sheet:" + gridkey, json.dumps({"data": init_json}))
            redis_obj.set_expireat(gridkey, save_time=3*24*60*60)
            mylog.info(f"inset into redis:{res}")
            init_json = json.dumps(init_json)
        return HttpResponse('%s' % init_json)


# 保存数据库处理
class LuckySheetSaveDb(View):
    def get(self, request):
        gridKey = request.GET.get("gridKey")
        mylog.info(f"Save file: {gridKey}")
        luckysheet_data = redis_obj.get_string("sheet:" + gridKey)
        if luckysheet_data:
            # MdFiles.objects.filter(upload_name=gridKey).update(text_content=luckysheet_data)
            res = MdFiles.objects.filter(upload_name=gridKey).exists()
            if not res:
                space_path = './static/markdown/common/excel/'
                gridKey_dec = gridKey.replace('.json', '.xlsx')
                data = {'doc_type': '.xlsx', 'space': 'common', 'upload_dir': space_path, 'upload_name': gridKey,
                        'cn_name': f'新文件 {gridKey_dec}'}
                MdFiles(**data).save()
                is_dir_exist(space_path)
                filepath = space_path + gridKey
            else:
                file = MdFiles.objects.filter(upload_name=gridKey).first()
                filepath = file.upload_dir + file.upload_name
                gridKey_dec = file.cn_name
            sheet_json = json.loads(luckysheet_data)
            write_json(filepath, sheet_json)
            res_info = f"{gridKey_dec} 保存成功!"
        else:
            res_info = "The gridkey does not exists %s" % gridKey
        return JsonResponse({"res_info": res_info})


def setRedis(request):
    key = request.GET.get('key')
    value = request.GET.get('value')
    res = redis_obj.insert_string(key=key, value=value)
    redis_obj.set_expireat(key, save_time=1 * 24 * 60 * 60)
    return JsonResponse({"status": res, "inser_key": key, "value": value})

def getRedis(request):
    key = request.GET.get('key')
    res = redis_obj.get_string(key=key)
    return HttpResponse(res)

def actRedis(request):
    cmd = request.GET.get('cmd')
    args = cmd.split(' ')
    res = redis_obj.act_command(*args)
    return JsonResponse({"result": res})